﻿using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Pay.Service.Service {
    /// <summary>
    /// 拓垦营销系统通用方法
    /// </summary>
    public class MarketingCommonService : ServiceBase, IMarketingCommonService, IDisposable {
        private IUnitOfWork _iUnitOfWork;
        private IMerchantService _merchantService;

        private readonly static object _getChildListLock = new object();
        public MarketingCommonService(IUnitOfWork iUnitOfWork, IMerchantService merchantService) : base(iUnitOfWork) {
            this._iUnitOfWork = iUnitOfWork;
            _merchantService = merchantService;
        }

        /// <summary>
        /// 根据商户Id获得其市级分公司
        /// </summary>
        /// <param name="merchantId"></param>
        /// <param name="isParentCity">如果当前公司是市级分公司，是否返回其父级分公司（系统默认市级公司），false则返回自身</param>
        /// <returns></returns>
        public merchant_dto GetCityCompanyMerchantByMerchantId(long merchantId, bool isParentCity = false) {
            merchant_dto merchant = _merchantService.Get(merchantId);
            //默认系统市级分公司
            merchant_dto defaultCityMerchant = _merchantService.Get(t_RequestMethod.TOKEN_MARKETING_DEFAULT_MEARCHANTNO);
            if (merchant.usertype == UserType.tokenCityAgent) {
                if (isParentCity == false)
                    return merchant;
                else
                    return defaultCityMerchant;
            }
            //找出第一个城市合伙人
            var parentCity = _merchantService.GetParents(merchant.id, false).FirstOrDefault(c => c.usertype == UserType.tokenCityAgent);
            if (parentCity != null) return parentCity;

            return defaultCityMerchant;
        }


        /// <summary>
        /// 获取我的直接下级
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="isDefautMerchantShowALL">系统默认账号是否显示Token所有商户</param>
        /// <param name="isFilterUserType">是否过滤用户角色（大于等于创客）</param>
        /// <returns></returns>
        public List<marketing_user_child_model> GetMyDirectChildList(long userId, bool isDefautMerchantShowALL = true, bool isFilterUserType = false) {
            lock (_getChildListLock) {
                var curMerchant = context.Merchants.FindById(userId);
                if (curMerchant.MerchantNo == t_RequestMethod.TOKEN_MARKETING_DEFAULT_MEARCHANTNO) {
                    var oem = context.Merchants.FirstOrDefault(c => c.MerchantNo == t_RequestMethod.merchant_no);
                    return context.Merchants
                     .Where(o => (isFilterUserType == false || (int)o.UserType >= (int)UserType.tokenMaker) && o.IsOEM == false && o.OemId == oem.Id && (isDefautMerchantShowALL || o.ParentId == 0))
                     .Select(o => new marketing_user_child_model() { Id = o.Id, ParentId = o.ParentId, UserType = o.UserType }).ToList();
                } else {
                    return context.Merchants
                                     .Where(o => (isFilterUserType == false || (int)o.UserType >= (int)UserType.tokenMaker) && o.ParentId == userId)
                                     .Select(o => new marketing_user_child_model() { Id = o.Id, ParentId = o.ParentId, UserType = o.UserType }).ToList();
                }
            }
        }

        /// <summary>
        /// 获取我的所有下级
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="isFilterUserType">是否过滤用户角色（大于等于创客）</param>
        /// <returns></returns>
        public List<marketing_user_child_model> GetMyAllChildList(long userId, bool isFilterUserType = false) {
            lock (_getChildListLock) {
                var curMerchant = context.Merchants.FindById(userId);
                if (curMerchant.MerchantNo == t_RequestMethod.TOKEN_MARKETING_DEFAULT_MEARCHANTNO) {
                    var oem = context.Merchants.FirstOrDefault(c => c.MerchantNo == t_RequestMethod.merchant_no);
                    return context.Merchants
                     .Where(o => (isFilterUserType == false || (int)o.UserType >= (int)UserType.tokenMaker) && o.IsOEM == false && o.OemId == oem.Id)
                     .Select(o => new marketing_user_child_model() { Id = o.Id, ParentId = o.ParentId, UserType = o.UserType }).ToList();
                } else {
                    var result = _merchantService.GetChilds(userId);
                    if (isFilterUserType) return result.Where(c => c.usertype >= UserType.tokenMaker).Select(o => new marketing_user_child_model() { Id = o.id, ParentId = o.parent_id, UserType = o.usertype }).ToList();
                    return result.Select(o => new marketing_user_child_model() { Id = o.id, ParentId = o.parent_id, UserType = o.usertype }).ToList();
                }
            }
        }
        /// <summary>
        /// 获取我的下级（我的市分公司下级，排除其的子级）
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="isFilterUserType">是否过滤用户角色（大于等于创客）</param>
        /// <returns></returns>
        public List<marketing_user_child_model> GetMyChidListNoHasCityChilds(long userId, bool isFilterUserType = false) {
            lock (_getChildListLock) {
                List<marketing_user_child_model> result = new List<marketing_user_child_model>();
                List<marketing_user_child_model> myChildList = GetMyAllChildList(userId, isFilterUserType);
                if (myChildList.Count() == 0) return result;

                //管理员的全部
                var curMerchant = _merchantService.Get(userId);
                if (curMerchant.merchant_no != t_RequestMethod.TOKEN_MARKETING_DEFAULT_MEARCHANTNO) return myChildList;

                GetHasCityChilds(myChildList, myChildList.Where(c => c.ParentId == userId));

                return _child_Models;
            }
        }

        private List<marketing_user_child_model> _child_Models = new List<marketing_user_child_model>();
        /// <summary>
        /// 下级市以上用户
        /// </summary>
        /// <param name="childList"></param>
        /// <param name="frists"></param>
        private void GetHasCityChilds(List<marketing_user_child_model> childList, IEnumerable<marketing_user_child_model> frists) {
            foreach (var item in frists) {
                _child_Models.Add(item);
                if (item.UserType <= UserType.tokenCityAgent) continue;
                GetHasCityChilds(childList, childList.Where(c => c.ParentId == item.Id));
            }
        }
    }
}
